package com.cloudcc.mobile.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.provider.CallLog;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StyleRes;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.cloudcc.cloudframe.util.DateUtils;
import com.cloudcc.mobile.ExtraConstant;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.ReceiverConstant;
import com.cloudcc.mobile.entity.CallLogEntity;
import com.cloudcc.mobile.entity.beau.BeauRecordTypeEntity;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.view.activity.BeauInfoActivity;
import com.cloudcc.mobile.view.activity.RecordtypeActivity;
import com.cloudcc.mobile.view.web.CloudWebViewActivity;
import com.cloudcc.mobile.view.web.WebSyncDefaultProxy;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.litesuits.android.log.Log;

import java.io.Serializable;
import java.util.List;

import butterknife.Bind;

/**
 * Created by lin on 2017/6/5.
 * <p>
 * 通话记录点击弹窗
 */

public class CallOutDialog extends Dialog implements View.OnClickListener {

    TextView callLogDialogName;
    TextView callLogDialogTime;
    TextView callLogDialogBt1;
    View callLogDialogBt1Line;
    View callLogDialogBt2Line;
    TextView callLogDialogBt2;

    private Context mcontext;
    private int whatBt = 1;//判断是哪个弹窗，默认是1
    private String ids, names, number, startTime, endTime;//详情页传递id


    private int jilusize;
    public List<BeauRecordTypeEntity.DataBean> DataBean_x;

    Handler handler;
    private int jurisdiction, jurisdiction4;//权限 ：1 所有 2查看 3没有

    public CallOutDialog(@NonNull Context context, @StyleRes int theme, int jurisdiction, int jurisdiction4) {
        super(context, theme);
        mcontext = context;
        handler = new Handler();
        this.jurisdiction = jurisdiction;
        this.jurisdiction4 = jurisdiction4;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ///设置为true点击区域外消失
        setContentView(R.layout.dialog_callout);

        setCanceledOnTouchOutside(true);// 点击Dialog外部消失

        callLogDialogName = (TextView) findViewById(R.id.call_log_dialog_name);
        callLogDialogTime = (TextView) findViewById(R.id.call_log_dialog_time);
        callLogDialogBt1 = (TextView) findViewById(R.id.call_log_dialog_bt1);
        callLogDialogBt1Line = findViewById(R.id.call_log_dialog_bt2_line);
        callLogDialogBt2Line = findViewById(R.id.call_log_dialog_bt2_line);
        callLogDialogBt2 = (TextView) findViewById(R.id.call_log_dialog_bt2);
        callLogDialogBt1.setOnClickListener(this);
        callLogDialogBt2.setOnClickListener(this);

    }

    public void setbt1(CallLogEntity data) {
        whatBt = 1;
        initShow(data);
        callLogDialogTime.setText(DateUtils.howMuchDay(mcontext, data.date) + " " + DateUtils.getHHMMTime(data.date));
        if (jurisdiction == 1) {
            callLogDialogBt1.setText(mcontext.getString(R.string.call_log_dialog_make));
        } else {
            callLogDialogBt1.setVisibility(View.GONE);
            callLogDialogBt1.setVisibility(View.GONE);
        }
        if (jurisdiction4 == 1) {
            callLogDialogBt2.setText(mcontext.getString(R.string.creat_qianzai_custom));
        } else {
            callLogDialogBt2Line.setVisibility(View.GONE);
            callLogDialogBt2.setVisibility(View.GONE);
        }
    }

    public void setbt2(CallLogEntity data) {
        whatBt = 2;
        initShow(data);
        callLogDialogTime.setText(DateUtils.howMuchDay(mcontext, data.date) + " " + DateUtils.getHHMMTime(data.date));
        callLogDialogBt1.setText(mcontext.getString(R.string.call_log_dialog_move_contacts));
        if (jurisdiction == 1) {
            callLogDialogBt2Line.setVisibility(View.VISIBLE);
            callLogDialogBt2.setVisibility(View.VISIBLE);
            callLogDialogBt2.setText(mcontext.getString(R.string.call_log_dialog_record_call));
        } else {
            callLogDialogBt2Line.setVisibility(View.GONE);
            callLogDialogBt2.setVisibility(View.GONE);
        }

    }

    private void initShow(CallLogEntity data) {
        ids = data.id;
        names = data.name;
        number = data.number;
        startTime = DateUtils.StringToString(data.date);
        endTime = DateUtils.addStartTime(startTime, Long.decode(data.duration));
        show();
        switch (data.type) {
            case CallLog.Calls.INCOMING_TYPE://打入
                callLogDialogName.setText(mcontext.getString(R.string.call_log_dialog_callin) + " " + (TextUtils.isEmpty(names) ? number : names));
                break;
            case CallLog.Calls.OUTGOING_TYPE://打出
                callLogDialogName.setText(mcontext.getString(R.string.call_log_dialog_callout) + " " + (TextUtils.isEmpty(names) ? number : names));
                break;
            case CallLog.Calls.MISSED_TYPE://未接
                callLogDialogName.setText(mcontext.getString(R.string.call_log_dialog_callmiss) + " " + (TextUtils.isEmpty(names) ? number : names));
                break;
        }
    }

    @Override
    public void onClick(View v) {
        if (v == callLogDialogBt1) {
            if (whatBt == 1) {//创建联系人

                if (jurisdiction == 1) {
                    setHttp("003");
                } else {
                    dismiss();
                }
            } else if (whatBt == 2) {//转到联系人
                Intent intent = new Intent(mcontext, BeauInfoActivity.class);
                intent.putExtra("web", ids);
                intent.putExtra("beau.nameid", "contact");
                if (jurisdiction == 1) {
                    intent.putExtra("callLog", "home");//只是返回变成Home按钮
                }
                mcontext.startActivity(intent);
            }
        }
        if (v == callLogDialogBt2) {
            if (whatBt == 1) {//创建潜在客户
                if (jurisdiction4 == 1) {
                    setHttp("004");
                } else {
                    dismiss();
                }
            } else if (whatBt == 2) {
                Intent intent = new Intent(mcontext, BeauInfoActivity.class);
                intent.putExtra("web", ids);
                intent.putExtra("callLog", "addphone");//返回变成Home按钮并且添加电话活动
                intent.putExtra("beau.nameid", "contact");
                intent.putExtra("beau.name", names);
                intent.putExtra("startTime", startTime);
                intent.putExtra("endTime", endTime);
                mcontext.startActivity(intent);
            }
        }
        dismiss();
    }


    /**
     * 记录类型网络请求
     */
    public void setHttp(final String prefix) {

        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance()
                .getServerBinding());
        params.addBodyParameter("serviceName", "getObjRecordTypeList");
        params.addBodyParameter("prefix", prefix);
        Log.d("列表值url-------------------------", UrlManager.getInterfaceUrl()
                + "?binding=" + RunTimeManager.getInstance().getServerBinding()
                + "&serviceName=getLookupValue"
                + "&objectId=2016360343BD7B2SQ2PO" + "&pageSize=1"
                + "&keyword=");
        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {

                        Log.d("列表值接口失败-------------------------", arg1);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        Log.d("列表值接口成功-------------------------", arg0.result);
                        Gson gson = new Gson();
                        BeauRecordTypeEntity mDdata = gson.fromJson(arg0.result.toString(),
                                BeauRecordTypeEntity.class);

                        android.util.Log.i("TAG", "aaaaaaaaa" + mDdata);
                        try {
                            jilusize = mDdata.getData().size();
                            DataBean_x = mDdata.getData();
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    creatLianxiren(prefix);
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                });

    }

    private void creatLianxiren(String prefix) {

        String mNewUrl = UrlManager.getManager()
                .getNewRecordUrl(prefix);
        if (jilusize < 2) {
            if (number.length() == 11) {
                mNewUrl = UrlManager.getManager()
                        .addReturnUrl(mNewUrl) + "&name=" + (TextUtils.isEmpty(names) ? "" : names) + (prefix.equals("003") ? "&shouji=" : "&phone=") + number;
            } else {
                mNewUrl = UrlManager.getManager()
                        .addReturnUrl(mNewUrl) + "&name=" + (TextUtils.isEmpty(names) ? "" : names) + "&dianhua=" + (TextUtils.isEmpty(number) ? "" : number);
            }

            Intent intent = new Intent(mcontext, CloudWebViewActivity.class);
            intent.putExtra(ExtraConstant.EXTRA_URL, mNewUrl);
            WebSyncDefaultProxy.MonitorParam monitorParam = new WebSyncDefaultProxy.MonitorParam(new String[]{"m=save"},
                    WebSyncDefaultProxy.STEP_START, new String[]{"m=query"},
                    true, WebSyncDefaultProxy.STEP_FINISH);
            intent.putExtra(
                    "callback",
                    WebSyncDefaultProxy
                            .creatDefaultProxy(ReceiverConstant.RECEIVE_REFRESH)
                            .addMonitorParam(monitorParam).addHomeMonitor());
            intent.putExtra("form", "calllog");
            mcontext.startActivity(intent);
        } else {
            Intent intent1 = new Intent(mcontext, RecordtypeActivity.class);
            Bundle jllx = new Bundle();
            jllx.putSerializable("JLLX", (Serializable) DataBean_x);
            jllx.putString("mEntityId", prefix);
            jllx.putString("MURL", mNewUrl);
            jllx.putString("name", names);
            jllx.putString("number", number);
            jllx.putString("form", "calllog");
            intent1.putExtras(jllx);
            mcontext.startActivity(intent1);

        }

    }
}
